package com.cnh.framework;

import com.cnh.framework.bean.Data;
import com.cnh.framework.bean.Handler;
import com.cnh.framework.bean.Param;
import com.cnh.framework.bean.View;
import com.cnh.framework.helper.BeanHelper;
import com.cnh.framework.helper.ConfigHelper;
import com.cnh.framework.helper.ControllerHelper;
import com.cnh.framework.util.*;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * 编写一个servlet，处理所有的请求。从HttpServletRequest对象中获取请求方法和路径，通过ControllerHelper#getHandler方法
 * 获取Handler对象。
 * 当拿到Handler对象后，可以获取到Controller类及其实例对象。
 * 随后可以从HttpServletRequest对象中获取所有请求参数，并将其初始化到一个Param的对象中。
 *
 * 实现一个简单的mvc框架
 */
//Servlet3.0支持使用注解，可以实现web.xml零配置
//所有请求都经由DispatcherServlet进行处理(/*)
@WebServlet(urlPatterns = "/*", loadOnStartup = 0)
public class DispatcherServlet extends HttpServlet {

    /**
     * 进行初始化，很重要
     * @param servletConfig
     * @throws ServletException
     */
    @Override
    public void init(ServletConfig servletConfig) throws ServletException {
        //初始化相关helper类
        HelperLoader.init();
        //获取ServletContext对象，用于注册servlet
        ServletContext servletContext = servletConfig.getServletContext();

        //注册处理JSP的servlet
        ServletRegistration jspServlet = servletContext.getServletRegistration("jsp");
        jspServlet.addMapping(ConfigHelper.getAppJspPath() + "*");

        //处理静态资源的默认Servlet
        ServletRegistration defaultServlet = servletContext.getServletRegistration("default");
        defaultServlet.addMapping(ConfigHelper.getAppAssetPath() + "*");
    }

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取请求方法与请求路径
        String requestMethod = request.getMethod().toLowerCase();
        String requestPath = request.getPathInfo();
        //获取Action处理器
        Handler handler = ControllerHelper.getHanlder(requestMethod, requestPath);
        if(handler != null){
            //获取Controller类及其Bean实例
            Class<?> controllerClass = handler.getControllerClass();
            Object controllerBean = BeanHelper.getBean(controllerClass);
            //创建请求参数对象
            Map<String, Object> paramMap = new HashMap<>();
            Enumeration<String> parameterNames = request.getParameterNames();
            while (parameterNames.hasMoreElements()){
                String paramName = parameterNames.nextElement();
                String paramValue = request.getParameter(paramName);

                paramMap.put(paramName, paramValue);
            }
            String body = CodecUtil.decodeURL(StreamUtil.getString(request.getInputStream()));
            if(StrUtil.isNotEmpty(body)){

                String[] params = StrUtil.splitString(body, "&");
                for (String param : params){

                    String[] array = StrUtil.splitString(param, "=");

                    if(ArrayUtil.isNotEmpty(array) && array.length == 2){
                        String paramName = array[0];
                        String paramValue = array[1];
                        paramMap.put(paramName, paramValue);
                    }
                }
            }
            Param param = new Param(paramMap);
            //调用Action方法
            Method actionMethod = handler.getActionMethod();
            Object result = ReflectionUtil.invokeMethod(controllerBean, actionMethod, param);
            //处理Action方法返回值
            if(result instanceof View){
                //返回jsp页面
                View view = (View) result;
                String path = view.getPath();
                if(StrUtil.isNotEmpty(path)){

                    if(path.startsWith("/")){
                        response.sendRedirect(request.getContextPath() + path);
                    } else {
                        Map<String, Object> model = view.getModel();

                        for (Map.Entry<String, Object> entry: model.entrySet()){
                            request.setAttribute(entry.getKey(), entry.getValue());
                        }
                        request.getRequestDispatcher(ConfigHelper.getAppJspPath() + path).forward(request, response);
                    }
                }
            } else if (result instanceof Data){
                // 返回JSON数据
                Data data = (Data) result;
                Object model = data.getModel();
                if(model!= null){
                    response.setContentType("application/json");
                    response.setCharacterEncoding("UTF-8");
                    PrintWriter writer = response.getWriter();
                    String json = JsonUtil.toJson(model);
                    writer.write(json);
                    writer.flush();
                    writer.close();
                }
            }
        }
    }
}
